<?php
declare (strict_types = 1);
namespace app\service;

use app\common\Service;

class WechatFansService extends Service
{
    public function saveInfo($data)
    {
        $openidInfo = $this->db->name('wechat_openid')->getInfo([
            'openid' => $data['openid'],
            'appid' => $data['appid'],
        ]);
        if (!empty($openidInfo)) {
            $fansId = $openidInfo['wechatfans_id'];
        } else if (!empty($data['unionid']) && !empty($fansInfo = $this->db->name('wechat_fans')->field('id')->getInfo(['unionid' => $data['unionid']]))) {
            $fansId = $fansInfo['id'];
        }
        $fansData = [
            'nickname' => $data['nickname'],
            'sex' => (int) $data['sex'],
            'language' => $data['language'],
            'city' => $data['city'],
            'province' => $data['province'],
            'country' => $data['country'],
            'headimgurl' => $data['headimgurl'],
        ];
        if (empty($fansId)) {
            $fansData['unionid'] = empty($data['unionid']) ? '' : $data['unionid'];
            $fansId = $this->db->name('wechat_fans')->insertGetId($fansData);
        } else {
            $this->db->name('wechat_fans')->saveInfo($fansData, $fansId);
        }
        if (empty($openidInfo)) {
            $this->db->name('wechat_openid')->insert([
                'wechatfans_id' => $fansId,
                'appid' => $data['appid'],
                'openid' => $data['openid'],
            ]);
        }
        return $fansId;
    }
}
